import {
  HEADER,
  CACHE_TOKEN,
  HTTP_REQUEST_FILE_URL
} from './../config.js';
import {
  getReLogin,
 
} from "../api/index.js"
const md5 = require('./md5code.js');

const signatureProcess = (data) => {
  let keys = Object.keys(data).sort()
  let query = keys.map(key => {
      return `${key}=${data[key]}`
  }).join('&')
  let signStr = md5.hexMD5(query).toUpperCase() + "code=APPStatic#@#&"
  let signFinal = md5.hexMD5(signStr).toUpperCase()
  return signFinal
}

const base64_decode = (input) => { // 解码，配合decodeURIComponent使用
  var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  var output = "";
  var chr1, chr2, chr3;
  var enc1, enc2, enc3, enc4;
  var i = 0;
  input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  while (i < input.length) {
      enc1 = base64EncodeChars.indexOf(input.charAt(i++));
      enc2 = base64EncodeChars.indexOf(input.charAt(i++));
      enc3 = base64EncodeChars.indexOf(input.charAt(i++));
      enc4 = base64EncodeChars.indexOf(input.charAt(i++));
      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;
      output = output + String.fromCharCode(chr1);
      if (enc3 != 64) {
          output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
          output = output + String.fromCharCode(chr3);
      }
  }
  return (output);
}

/**
* 发送请求
*/
/**
* 发送请求
*/
export default function requestFile(url, param, callback) {
  console.log('发送请求：', url, param);

  const commonParams = {
      sys_type: 'app',
      version_name: '6.16.0',
      client_device: 'wechat_xcx',
      timestamp: parseInt(Date.now() / 1000),
      token: wx.getStorageSync(CACHE_TOKEN)
  }
  const sendParams = Object.assign(commonParams, param.data)
  sendParams['sign'] = signatureProcess(sendParams)
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: HTTP_REQUEST_FILE_URL + url,
      filePath: url,
      name: 'imgFile',
      header: {
        "Content-Type": "multipart/form-data"
      },
      formData: commonParams,
      success: function (res) {
        res.data = JSON.parse(res.data)
        res.data.data = JSON.parse(that.base64_decode(res.data.data))
        console.log('res', res)
        resolve(res.data.data)
      },
      fail: function(err) {
          console.error('请求失败', err);
          reject(err)
      }
    })
    wx.hideLoading();
  })
}

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect', 'upload'].forEach((method) => {
  requestFile[method] = (api, data, opt, callback) => {
      const token = opt && opt.token ? opt.token : '';
      return requestFile(api, {
          method,
          data,
          token
      }, callback);
  };
});
